import { useHistory } from "react-router";
import { NavBar, SearchBar } from "antd-mobile";

import Icon from "@/components/Icon";
import styles from "./index.module.scss";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getSuggestion } from "@/store/actions/search";
import { useDebounceFn } from "ahooks";
import { RootState } from "@/types/store";
import classNames from "classnames";
const SearchPage = () => {
    const history = useHistory();
    // 收集输入框内容
    const [searchText, setSearchText] = useState("");
    // 输入框变化
    const dispatch = useDispatch();
    const onSearchChange = (value: string) => {
        setSearchText(value);
        debounceGetSuggest(value);
    };
    //防抖
    const { run: debounceGetSuggest } = useDebounceFn(
        (value: string) => {
            dispatch(getSuggestion(value.trim()));
        },
        {
            wait: 500,
        }
    );
    // 获取搜索建议结果
    const { suggestion } = useSelector((state: RootState) => state.search);
    // 封装高亮
    const highLight = (str: string, keyword: string) => {
        const reg = new RegExp(keyword, "gi");
        return str.replace(reg, (match) => {
            return `<span style="color: red;">${match}</span>`;
        });
    };
    const onSearch = (value: string) => {
        history.push(`/search/result?q=${value}`);
        saveHistories(value);
        dispatch(getSuggestion(""));
    };
    const GEEK_SEARCH_KEY = "geek_search_key";
    // 保存历史记录
    const saveHistories = (value: string) => {
        const localHistories = JSON.parse(
            localStorage.getItem(GEEK_SEARCH_KEY) ?? "[]"
        ) as string[];
        let histories: string[] = [];
        if (localHistories.length === 0) {
            histories = [value];
        } else {
            const index = localHistories.indexOf(value) >= 0;
            if (index) {
                const leftHistories = localHistories.filter(
                    (item) => item !== value
                );
                histories = [value, ...leftHistories];
            } else {
                histories = [value, ...localHistories];
            }
        }
        localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(histories));
    };
    // 历史记录
    const [searchHistory, setSearchHistory] = useState<string[]>([]);
    useEffect(() => {
        const histories = JSON.parse(
            localStorage.getItem(GEEK_SEARCH_KEY) ?? "[]"
        ) as string[];

        setSearchHistory(histories);
    }, []);
    // 删除历史记录
    const onDeleteHistory = (value: string) => {
        const newSearchHistory = searchHistory.filter((item) => item !== value);
        setSearchHistory(newSearchHistory);
        localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(newSearchHistory));
    };
    // 清空历史记录
    const onClearHistory = () => {
        setSearchHistory([]);
        localStorage.removeItem(GEEK_SEARCH_KEY);
    };
    return (
        <div className={styles.root}>
            <NavBar
                className="navbar"
                onBack={() => history.go(-1)}
                right={
                    <span
                        className="search-text"
                        onClick={() => onSearch(searchText)}>
                        搜索
                    </span>
                }>
                <SearchBar
                    value={searchText}
                    placeholder="请输入关键字搜索"
                    onChange={onSearchChange}
                />
            </NavBar>

            {suggestion.length <= 0 && (
                <div
                    className="history"
                    style={{
                        display: searchHistory.length <= 0 ? "none" : "block",
                    }}>
                    <div className="history-header">
                        <span>搜索历史</span>
                        <span onClick={onClearHistory}>
                            <Icon type="iconbtn_del" />
                            清除全部
                        </span>
                    </div>

                    <div className="history-list">
                        {searchHistory.map((item, index) => (
                            <div key={index} className="history-item">
                                <span className="text-overflow">{item}</span>
                                <Icon
                                    type="iconbtn_essay_close"
                                    onClick={() => onDeleteHistory(item)}
                                />
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div
                className={classNames("search-result", {
                    show: suggestion.length > 0,
                })}>
                {suggestion.map((item, index) => (
                    <div
                        key={index}
                        className="result-item"
                        onClick={() => onSearch(searchText)}>
                        <Icon className="icon-search" type="iconbtn_search" />
                        {/*  
                        react中渲染html内容
                        */}
                        <div
                            className="result-value"
                            dangerouslySetInnerHTML={{
                                __html: item ? highLight(item, searchText) : "",
                            }}></div>
                    </div>
                ))}
            </div>
        </div>
    );
};

export default SearchPage;
